package com.jiang.ws;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @类名称 EchoWebSocket
 * @类功能描述
 * @作者 蒋正午
 * @日期 2019-01-20  18:51
 */
@ServerEndpoint("/echo")
public class EchoWebSocket {

    private static Set<Session> sessions = new HashSet<>();

    @OnOpen
    public void open(Session session){
        // 打开连接
        System.out.println("*****************" + session.getId());
        sessions.add(session);
    }

    @OnMessage
    public void messgeHandler(String msg){

        System.out.println("处理数据" + msg);
        try {
            // 给所有的前端发送数据
            for(Session _session: sessions){
                _session.getBasicRemote().sendText("[echo]" + msg);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @OnClose
    public void close(Session session){
        // 关闭连接
        System.out.println("******************" + session.getId());
    }


}
